package com.JumpAndJump.controller;

import com.JumpAndJump.common.ServerResponse;
import com.JumpAndJump.pojo.User;
import com.JumpAndJump.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * Created by Abbott on 2018/1/7.
 */

@Controller
@RequestMapping("/user/")
public class UserController {


    @Autowired
    private IUserService iUserService;


    /**
     * 用户登录
     * @param username
     * @param password
     * @param session
     * @return
     */
    @RequestMapping(value = "login.do",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<User> login(String username, String password, HttpSession session){

        ServerResponse<User> response = iUserService.login(username,password);
        if(response.isSuccess()){
            session.setAttribute("CURRENT_USER",response.getData());
            session.setAttribute("UserID",response.getMsg());
        }
        return response;
    }

    @RequestMapping(value = "register.do",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> register(String username,String password){

        return iUserService.register(username,password);
    }

    @RequestMapping(value = "selectUsername.do",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<String> selectUsername(String username){
        return iUserService.checkValidUsername(username);
    }


    @RequestMapping(value = "ifLoginIn.do",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<User> ifLoginIn( HttpSession session){
        if(session.getAttribute("CURRENT_USER") != null){
            return ServerResponse.createBySuccessMessage("1");
        }
        return ServerResponse.createByErrorMessage("0");
    }

    @RequestMapping(value = "getUserInfo.do",method = RequestMethod.POST)
    @ResponseBody
    public ServerResponse<Object> getUserInfo( HttpSession session){
        if(session.getAttribute("CURRENT_USER") != null){
            return ServerResponse.createBySuccess(session.getAttribute("CURRENT_USER"));
        }
        return ServerResponse.createByErrorMessage("当前未登录");
    }

}
